<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElTabs, ElTabPane, ElRow, ElCol, ElCard, ElImage, ElIcon, ElAvatar, ElEmpty, ElPagination, ElMessage, ElSkeleton, ElSkeletonItem } from 'element-plus';
import { Coin, User, Picture as IconPicture } from '@element-plus/icons-vue';
import courseService from '@/services/courseService.js';
import { userManager } from '@/utils/user.js';

const router = useRouter();
const currentUser = ref(null);

const activeTab = ref('selected');

// 教师创建的课程
const createdCourses = ref([]);
const createdPagination = reactive({ page: 1, pageSize: 12, total: 0 });
const createdLoading = ref(true);

// 学生加入的课程
const selectedCourses = ref([]);
const selectedPagination = reactive({ page: 1, pageSize: 12, total: 0 });
const selectedLoading = ref(true);

const fetchCreatedCourses = async () => {
  if (!currentUser.value || currentUser.value.userType !== 1) return;
  createdLoading.value = true;
  try {
    const params = { page: createdPagination.page, size: createdPagination.pageSize, teacherId: userManager.getUserId() };
    const res = await courseService.getCourseList(params);
    if (res.success) {
      createdCourses.value = res.data.records || [];
      createdPagination.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取创建的课程失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    createdLoading.value = false;
  }
};

const fetchSelectedCourses = async () => {
  if (!currentUser.value) return;
  selectedLoading.value = true;
  try {
    const params = { page: selectedPagination.page, size: selectedPagination.pageSize };
    const res = await courseService.getSelectedCoursesByUserId(userManager.getUserId(), params);
    if (res.success) {
      selectedCourses.value = res.data.records || [];
      selectedPagination.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取加入的课程失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    selectedLoading.value = false;
  }
};

const handleTabChange = (tabName) => {
  if (tabName === 'created' && createdCourses.value.length === 0) fetchCreatedCourses();
  else if (tabName === 'selected' && selectedCourses.value.length === 0) fetchSelectedCourses();
};

const handleCreatedPageChange = (page) => {
  createdPagination.page = page;
  fetchCreatedCourses();
};

const handleSelectedPageChange = (page) => {
  selectedPagination.page = page;
  fetchSelectedCourses();
};

const goToCourseDetail = (courseId) => router.push(`/course/${courseId}`);

onMounted(() => {
  currentUser.value = userManager.getUserInfo();
  if (currentUser.value) {
    activeTab.value = currentUser.value.userType === 0 ? 'selected' : 'created';
    if (activeTab.value === 'created') fetchCreatedCourses();
    fetchSelectedCourses();
  } else {
    ElMessage.warning('请先登录');
    router.push('/');
  }
});
</script>

<template>
  <div class="page-background">
    <div class="content-panel">
      <div class="page-header">
        <h1>我的课程</h1>
        <p>管理您创建和加入的所有课程</p>
      </div>

      <el-tabs v-model="activeTab" class="google-style-tabs" @tab-change="handleTabChange">
        <el-tab-pane label="我加入的课程" name="selected" v-if="currentUser && currentUser.userType === 0" >
          <div v-if="selectedLoading" class="skeleton-grid">
            <el-card v-for="n in 8" :key="n" shadow="never" class="skeleton-card">
              <el-skeleton animated>
                <template #template>
                  <el-skeleton-item variant="image" style="width: 100%; height: 140px;" />
                  <div style="padding: 14px 0 0 0;">
                    <el-skeleton-item variant="p" style="width: 70%" />
                    <el-skeleton-item variant="text" style="width: 40%; margin-top: 8px;" />
                  </div>
                </template>
              </el-skeleton>
            </el-card>
          </div>
          <el-empty v-else-if="selectedCourses.length === 0" description="您还没有加入任何课程">
            <el-button type="primary" @click="router.push('/search-course')">去逛逛</el-button>
          </el-empty>
          <div v-else>
            <el-row :gutter="24">
              <el-col v-for="course in selectedCourses" :key="course.id" :xs="24" :sm="12" :md="8" :lg="6">
                <div class="course-card" @click="goToCourseDetail(course.id)">
                  <el-image :src="course.image" fit="cover" class="course-image">
                    <template #error><div class="image-error-slot"><el-icon><IconPicture /></el-icon></div></template>
                  </el-image>
                  <div class="course-info">
                    <h4 class="course-title" :title="course.name">{{ course.name }}</h4>
                    <div class="course-meta">
                      <div class="author-info">
                        <el-avatar :size="24" :src="course.teacherAvatar" />
                        <span>{{ course.teacherName || '未知教师' }}</span>
                      </div>
                      <div class="credit-info">
                        <el-icon><Coin /></el-icon>
                        <span>{{ course.credit || 0 }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-pagination
                v-if="selectedPagination.total > selectedPagination.pageSize"
                background layout="prev, pager, next" :total="selectedPagination.total"
                :page-size="selectedPagination.pageSize" :current-page="selectedPagination.page"
                @current-change="handleSelectedPageChange" class="pagination-container"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="我创建的课程" name="created" v-if="currentUser && currentUser.userType === 1">
          <div v-if="createdLoading" class="skeleton-grid">
            <el-card v-for="n in 8" :key="n" shadow="never" class="skeleton-card">
              <el-skeleton animated>
                <template #template>
                  <el-skeleton-item variant="image" style="width: 100%; height: 140px;" />
                  <div style="padding: 14px 0 0 0;">
                    <el-skeleton-item variant="p" style="width: 70%" />
                    <el-skeleton-item variant="text" style="width: 40%; margin-top: 8px;" />
                  </div>
                </template>
              </el-skeleton>
            </el-card>
          </div>
          <el-empty v-else-if="createdCourses.length === 0" description="您还没有创建任何课程">
            <el-button type="primary" @click="router.push('/new-course')">立即创建</el-button>
          </el-empty>
          <div v-else>
            <el-row :gutter="24">
              <el-col v-for="course in createdCourses" :key="course.id" :xs="24" :sm="12" :md="8" :lg="6">
                <div class="course-card" @click="goToCourseDetail(course.id)">
                  <el-image :src="course.image" fit="cover" class="course-image">
                    <template #error><div class="image-error-slot"><el-icon><IconPicture /></el-icon></div></template>
                  </el-image>
                  <div class="course-info">
                    <h4 class="course-title" :title="course.name">{{ course.name }}</h4>
                    <div class="course-meta">
                      <div class="author-info">
                        <el-avatar :size="24" :src="course.teacherAvatar" />
                        <span>{{ currentUser.username }}</span>
                      </div>
                      <div class="credit-info">
                        <el-icon><Coin /></el-icon>
                        <span>{{ course.credit || 0 }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-pagination
                v-if="createdPagination.total > createdPagination.pageSize"
                background layout="prev, pager, next" :total="createdPagination.total"
                :page-size="createdPagination.pageSize" :current-page="createdPagination.page"
                @current-change="handleCreatedPageChange" class="pagination-container"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.page-background { background-color: #f7f8fa; min-height: 100vh; padding: 24px; }
.content-panel { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 24px 32px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
.page-header { margin-bottom: 20px; }
.page-header h1 { font-size: 24px; font-weight: 500; color: #202124; }
.page-header p { font-size: 14px; color: #5f6368; margin-top: 8px; }

/* Google风格Tabs */
.google-style-tabs { border-bottom: 1px solid #e4e7ed; }
.google-style-tabs :deep(.el-tabs__header) { margin: 0 0 24px 0; }
.google-style-tabs :deep(.el-tabs__nav-wrap::after) { content: none; }
.google-style-tabs :deep(.el-tabs__item) { padding: 0 16px !important; height: 44px; font-size: 15px; color: #5f6368; }
.google-style-tabs :deep(.el-tabs__item.is-active) { color: var(--el-color-primary); }
.google-style-tabs :deep(.el-tabs__active-bar) { height: 3px; border-radius: 3px; }

/* 课程卡片 */
.course-card { background-color: #fff; border-radius: 10px; box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 1px 3px 1px rgba(60,64,67,0.15); transition: box-shadow 0.3s ease; cursor: pointer; position: relative; overflow: hidden; margin-bottom: 24px; }
.course-card::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; opacity: 0; transition: opacity 0.3s ease; pointer-events: none; }
.course-card:hover::after { opacity: 0.04; }
.course-image { width: 100%; height: 140px; display: block; background-color: #f1f3f4; }
.image-error-slot { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; color: #c0c4cc; font-size: 30px; }
.course-info { padding: 16px; }
.course-title { font-size: 1rem; font-weight: 500; color: #202124; margin: 0 0 12px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.course-meta { display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #5f6368; }
.author-info, .credit-info { display: flex; align-items: center; gap: 6px; }

/* 骨架屏 */
.skeleton-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 24px; }
.skeleton-card { border-radius: 16px; border: none; padding: 0; overflow: hidden; }
.skeleton-card :deep(.el-skeleton) { padding: 0; }

.pagination-container { margin-top: 24px; display: flex; justify-content: center; }
</style>